package com.madixin.chat.service.impl;

import com.madixin.chat.exception.ChatBaseException;
import com.madixin.chat.exception.ErrorCode;
import com.madixin.chat.security.LoginUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service
public class LoginService {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginService.class);

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtService jwtService;

    public String login(String username, String password) throws ChatBaseException {
        // 该方法会去调用UserDetailsService.loadUserByUsername
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        LoginUserDetails loginUser = (LoginUserDetails) authentication.getPrincipal();
        if (loginUser == null){
            throw new ChatBaseException(ErrorCode.ILLEGAL_AUTHENTICATE);// 认证失败
        }
        return jwtService.generateToken(loginUser);
    }

    public void logout() throws ChatBaseException {

    }
}
